package com.lvhx.springboot.base;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public abstract class CurrentUnitOfWork {
    private static final ThreadLocal<CalledService> _CALLEDSVC = new ThreadLocal<CalledService>(){
        protected CalledService initialValue(){
            return new CalledService();
        }
    };

    private static final ThreadLocal<UnitOfWork> CURRENT = new ThreadLocal<>();

    private static final ThreadLocal<Map<String,Object>> CACHE = new ThreadLocal<Map<String,Object>>(){
        protected Map<String,Object> initialValue(){
            return new HashMap<>();
        }
    };

    private CurrentUnitOfWork(){

    }

    public static boolean isStarted(){
        return CURRENT.get() != null;
    }

    public static UnitOfWork get(){
        if (CURRENT.get() == null){
            throw  new IllegalStateException("No UnitOfWork is Currently started for this thread.");

        }
        return CURRENT.get();
    }


    public static void commit(){
        get().commit();
    }
    public static void set(UnitOfWork unitOfWork){
        CURRENT.set(unitOfWork);
    }

    public static Map<String,Object> getCache(){
        return CACHE.get();
    }

    public static void cleatCache(){
        getCache().clear();
    }

    public static void clear(UnitOfWork unitOfWork){
        if (isStarted() && CURRENT.get() == unitOfWork){
            CURRENT.remove();
            cleatCache();
        }else {
            throw  new IllegalStateException("Could not clear this UnitOfWork. It is not the active one.");
        }
    }

    public static void saveCalledService(Method m,Object[] args){
        _CALLEDSVC.get().setM(m);
        _CALLEDSVC.get().setArgs(args);
    }

    public static Object[] getCalledServiceArgs(){
        return _CALLEDSVC.get().getArgs();
    }

    public static Method getCalledServiceMethod(){
        return _CALLEDSVC.get().getM();
    }

    public static void clearCalledService(){
        _CALLEDSVC.remove();
    }
}
